package mi.payment.ui.other;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import java.io.IOException;

import lainey.ui.widget.TitleView;
import mi.payment.R;
import mi.payment.constants.Configs;
import mi.payment.ui.print.helper.PrintController;
import mi.payment.db.PayDetailModel;
import mi.payment.db.dao.PayDetail;
import mi.payment.ui.base.PageRoute;
import mi.payment.ui.base.ParentActivity;
import mi.payment.ui.view.LinePathView;
import mi.payment.utils.BitmapUtils;
import mi.payment.utils.MoneyUtils;
import sunmi.sunmiui.utils.LogUtil;

/**
 * 电子签名Activity
 */
public class HandWriteActivity extends ParentActivity {

    private Button mBtnSave;
    private LinePathView mLlPathView;

    private int mType;
    private PayDetail mPayDetail;
    private String mTransFeatureCode;

    public static int sCountTime = 60;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            sCountTime--;
            if (sCountTime > 0) {
                String text = getString(R.string.save) + "(" + sCountTime + "S)";
                mBtnSave.setText(text);
                mHandler.sendEmptyMessageDelayed(0, 1000);
            } else {
                mHandler.removeMessages(0);
                showToast(R.string.signature_timeout);
                mBtnSave.setText(R.string.save);
                signatureSSuccess();
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hand_write);
        initView();
        sCountTime = 60;
        mHandler.sendEmptyMessage(0);
    }

    private void initView() {
        mType = getIntent().getIntExtra("extra_type", PageRoute.TYPE_CONSUME);
        mPayDetail = (PayDetail) getIntent().getSerializableExtra("extra_payDetail");

        String disAmount = MoneyUtils.longCent2DoubleMoneyStr(mPayDetail.amount);
        mTransFeatureCode = new PrintController().generateTransFeatureCode(mPayDetail); // 电子签名特征码
        LogUtil.d(Configs.TAG, "disAmount:" + disAmount + "---mTransFeatureCode:" + mTransFeatureCode);

        TitleView titleView = findViewById(R.id.title_view);
        titleView.setLeftImageVisibility(View.GONE);
        String text = getString(R.string.consume) + getString(R.string.money_symbol) + disAmount;
        titleView.setCenterText(text);

        mLlPathView = findViewById(R.id.line_path_view);
        mLlPathView.updateTransFeatureCode(mTransFeatureCode);

        Button clear = findViewById(R.id.btn_clear);
        clear.setOnClickListener(
                v -> {
                    sCountTime = 60;
                    mLlPathView.clear();
                    mLlPathView.updateTransFeatureCode(mTransFeatureCode);
                }

        );
        mBtnSave = findViewById(R.id.btn_save);
        mBtnSave.setOnClickListener(
                v -> {
                    boolean touched = mLlPathView.getTouched(); // 是否有签名
                    boolean isValidSignature = mLlPathView.getIsValidSignature(); // 是否是有效签名
                    if (touched) {
                        if (isValidSignature) {
                            try {
                                Bitmap cacheBitmap = mLlPathView.getCacheBitmap();
                                cacheBitmap = BitmapUtils.scale(cacheBitmap, cacheBitmap.getWidth() / 3, cacheBitmap.getHeight() / 3);
                                String jBigHex = BitmapUtils.bitmap2JBigHex(cacheBitmap);
                                saveESignJBigHex2DB(jBigHex);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            signatureSSuccess();
                        } else {
                            showToast(R.string.signature_too_sample);
                        }
                    } else {
                        showToast(R.string.signature_no_data);
                    }
                }
        );
    }

    /**
     * 保存电子签名和电子签名是否有效到数据库
     */
    private void saveESignJBigHex2DB(String data) {
        PayDetailModel payDetailModel = PayDetailModel.getInstance();
        PayDetail payDetail = payDetailModel.getLastData();
        payDetail.seteSignHexData(data);
        payDetailModel.update(payDetail);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onBackPressed() {
        signatureSSuccess();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    private void signatureSSuccess() {
        PageRoute.success(this, mType, mPayDetail);
        finish();
    }

    public static void startAction(Context context, int type, PayDetail payDetail) {
        Intent intent = new Intent(context, HandWriteActivity.class);
        intent.putExtra("extra_type", type);
        intent.putExtra("extra_payDetail", payDetail);
        context.startActivity(intent);
    }


}
